package com.xncoding.RateLimiter;

import java.util.concurrent.*;

public class MyRateLimiter {
    //令牌桶
    BlockingQueue<Integer> TOKEN_BUCKET = new LinkedBlockingDeque<>(5);

    public static void main(String[] args) {
        MyRateLimiter myRateLimiter=new MyRateLimiter();
        myRateLimiter.addTokenFixedRate();
        for(int i=0;i<10;i++){
            myRateLimiter.acqurie();
            System.out.println("第几次执行i:" + i + ",执行时间为：" + System.currentTimeMillis());
        }
    }
    /**
     * 定时添加令牌
     */
    public void addTokenFixedRate(){
        ScheduledExecutorService scheduledExecutorService= Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(()->{
            boolean suc=TOKEN_BUCKET.offer(1);
            if(!suc){
                System.out.println("令牌桶满了丢弃");
            }
        },0,200,TimeUnit.MILLISECONDS);
    }

    public void acqurie(){
        while (TOKEN_BUCKET.poll()==null){};
    }

}
